const axios = require('axios');

// 测试配置
const BASE_URL = 'http://localhost:3001';
const TEST_USER_ID = 'test_user_123';
const TEST_ORDER_ID = 'test_order_001';

// 测试用的JWT token（如果需要的话）
const TEST_TOKEN = 'test_token';

// 创建axios实例
const api = axios.create({
  baseURL: BASE_URL,
  headers: {
    'Content-Type': 'application/json',
    'token': TEST_TOKEN
  }
});

// 测试结果统计
let totalTests = 0;
let passedTests = 0;
let failedTests = 0;

// 测试辅助函数
function logTest(testName, passed, response = null, error = null) {
  totalTests++;
  if (passed) {
    passedTests++;
    console.log(`✅ ${testName} - PASSED`);
    if (response && response.data) {
      console.log(`   Response: ${JSON.stringify(response.data, null, 2)}`);
    }
  } else {
    failedTests++;
    console.log(`❌ ${testName} - FAILED`);
    if (error) {
      console.log(`   Error: ${error.message}`);
    }
    if (response && response.data) {
      console.log(`   Response: ${JSON.stringify(response.data, null, 2)}`);
    }
  }
  console.log('---');
}

// 测试函数
async function testOrderList() {
  console.log('\n🧪 测试订单列表接口 GET /api/order/list');
  
  try {
    // 测试正常请求
    const response = await api.get(`/api/order/list?userid=${TEST_USER_ID}&page=1&pageSize=10`);
    logTest('订单列表 - 正常请求', response.data.code === '200', response);
    
    // 测试状态筛选
    const statusResponse = await api.get(`/api/order/list?userid=${TEST_USER_ID}&status=1`);
    logTest('订单列表 - 状态筛选', statusResponse.data.code === '200', statusResponse);
    
    // 测试缺少userid参数
    const noUserResponse = await api.get('/api/order/list');
    logTest('订单列表 - 缺少userid', noUserResponse.data.code === '400', noUserResponse);
    
  } catch (error) {
    logTest('订单列表接口测试', false, null, error);
  }
}

async function testOrderDetail() {
  console.log('\n🧪 测试订单详情接口 GET /api/order/detail/:orderid');
  
  try {
    // 测试正常请求
    const response = await api.get(`/api/order/detail/${TEST_ORDER_ID}?userid=${TEST_USER_ID}`);
    logTest('订单详情 - 正常请求', response.data.code === '200' || response.data.code === '404', response);
    
    // 测试缺少userid参数
    const noUserResponse = await api.get(`/api/order/detail/${TEST_ORDER_ID}`);
    logTest('订单详情 - 缺少userid', noUserResponse.data.code === '400', noUserResponse);
    
  } catch (error) {
    logTest('订单详情接口测试', false, null, error);
  }
}

async function testOrderSearch() {
  console.log('\n🧪 测试订单搜索接口 GET /api/order/search');
  
  try {
    // 测试正常搜索
    const response = await api.get(`/api/order/search?userid=${TEST_USER_ID}&keyword=test`);
    logTest('订单搜索 - 正常请求', response.data.code === '200', response);
    
    // 测试空关键词
    const emptyKeywordResponse = await api.get(`/api/order/search?userid=${TEST_USER_ID}&keyword=`);
    logTest('订单搜索 - 空关键词', emptyKeywordResponse.data.code === '200', emptyKeywordResponse);
    
    // 测试缺少userid参数
    const noUserResponse = await api.get('/api/order/search?keyword=test');
    logTest('订单搜索 - 缺少userid', noUserResponse.data.code === '400', noUserResponse);
    
  } catch (error) {
    logTest('订单搜索接口测试', false, null, error);
  }
}

async function testUpdateOrderStatus() {
  console.log('\n🧪 测试订单状态更新接口 POST /api/order/updateStatus');
  
  try {
    // 测试正常状态更新
    const response = await api.post('/api/order/updateStatus', {
      orderid: TEST_ORDER_ID,
      userid: TEST_USER_ID,
      status: 1
    });
    logTest('状态更新 - 正常请求', response.data.code === '200' || response.data.code === '404' || response.data.code === '400', response);
    
    // 测试无效状态值
    const invalidStatusResponse = await api.post('/api/order/updateStatus', {
      orderid: TEST_ORDER_ID,
      userid: TEST_USER_ID,
      status: 99
    });
    logTest('状态更新 - 无效状态', invalidStatusResponse.data.code === '400', invalidStatusResponse);
    
    // 测试缺少参数
    const missingParamsResponse = await api.post('/api/order/updateStatus', {
      orderid: TEST_ORDER_ID
    });
    logTest('状态更新 - 缺少参数', missingParamsResponse.data.code === '400', missingParamsResponse);
    
  } catch (error) {
    logTest('订单状态更新接口测试', false, null, error);
  }
}

async function testCancelOrder() {
  console.log('\n🧪 测试订单取消接口 POST /api/order/cancel');
  
  try {
    // 测试正常取消
    const response = await api.post('/api/order/cancel', {
      orderid: TEST_ORDER_ID,
      userid: TEST_USER_ID,
      reason: '测试取消'
    });
    logTest('订单取消 - 正常请求', response.data.code === '200' || response.data.code === '404' || response.data.code === '400', response);
    
    // 测试缺少参数
    const missingParamsResponse = await api.post('/api/order/cancel', {
      orderid: TEST_ORDER_ID
    });
    logTest('订单取消 - 缺少参数', missingParamsResponse.data.code === '400', missingParamsResponse);
    
  } catch (error) {
    logTest('订单取消接口测试', false, null, error);
  }
}

async function testConfirmOrder() {
  console.log('\n🧪 测试确认收货接口 POST /api/order/confirm');
  
  try {
    // 测试正常确认收货
    const response = await api.post('/api/order/confirm', {
      orderid: TEST_ORDER_ID,
      userid: TEST_USER_ID
    });
    logTest('确认收货 - 正常请求', response.data.code === '200' || response.data.code === '404' || response.data.code === '400', response);
    
    // 测试缺少参数
    const missingParamsResponse = await api.post('/api/order/confirm', {
      orderid: TEST_ORDER_ID
    });
    logTest('确认收货 - 缺少参数', missingParamsResponse.data.code === '400', missingParamsResponse);
    
  } catch (error) {
    logTest('确认收货接口测试', false, null, error);
  }
}

async function testOrderStatistics() {
  console.log('\n🧪 测试订单统计接口 GET /api/order/statistics');
  
  try {
    // 测试正常请求
    const response = await api.get(`/api/order/statistics?userid=${TEST_USER_ID}`);
    logTest('订单统计 - 正常请求', response.data.code === '200', response);
    
    // 测试缺少userid参数
    const noUserResponse = await api.get('/api/order/statistics');
    logTest('订单统计 - 缺少userid', noUserResponse.data.code === '400', noUserResponse);
    
  } catch (error) {
    logTest('订单统计接口测试', false, null, error);
  }
}

async function testStatusCount() {
  console.log('\n🧪 测试状态数量统计接口 GET /api/order/statusCount');
  
  try {
    // 测试正常请求
    const response = await api.get(`/api/order/statusCount?userid=${TEST_USER_ID}`);
    logTest('状态统计 - 正常请求', response.data.code === '200', response);
    
    // 测试缺少userid参数
    const noUserResponse = await api.get('/api/order/statusCount');
    logTest('状态统计 - 缺少userid', noUserResponse.data.code === '400', noUserResponse);
    
  } catch (error) {
    logTest('状态数量统计接口测试', false, null, error);
  }
}

// 主测试函数
async function runAllTests() {
  console.log('🚀 开始测试新实现的订单管理接口\n');
  console.log('='.repeat(50));
  
  await testOrderList();
  await testOrderDetail();
  await testOrderSearch();
  await testUpdateOrderStatus();
  await testCancelOrder();
  await testConfirmOrder();
  await testOrderStatistics();
  await testStatusCount();
  
  console.log('\n' + '='.repeat(50));
  console.log('📊 测试结果统计:');
  console.log(`总测试数: ${totalTests}`);
  console.log(`通过: ${passedTests}`);
  console.log(`失败: ${failedTests}`);
  console.log(`成功率: ${((passedTests / totalTests) * 100).toFixed(2)}%`);
  
  if (failedTests === 0) {
    console.log('\n🎉 所有测试通过！');
  } else {
    console.log('\n⚠️  部分测试失败，请检查实现。');
  }
}

// 运行测试
if (require.main === module) {
  runAllTests().catch(console.error);
}

module.exports = {
  runAllTests,
  testOrderList,
  testOrderDetail,
  testOrderSearch,
  testUpdateOrderStatus,
  testCancelOrder,
  testConfirmOrder,
  testOrderStatistics,
  testStatusCount
};